var shopArray = [
    {code:1,name:"面包",price:4,num:5},
    {code:2,name:"火腿",price:6,num:8},
    {code:3,name:"牛奶",price:5,num:12},
    {code:4,name:"水",price:3,num:4}
]
function $(id) {
    return document.getElementById(id);
}

window.onload = function () {
    showShop();
    totalShop();
}

/**
 * 显示购物车信息
 */
function showShop() {
    var str = "";
    shopArray.forEach(n => {
        str += `<tr><td>${n.code}</td><td>${n.name}</td><td>${n.price}</td>
                        <td><input type="number" min="1" value="${n.num}" id="shopNum" onblur="updateNum(${n.code})"></td>
                        <td>${n.price * n.num}</td><td><input type="button" value="移除商品" onclick="del(${n.code})"></td></tr>`;
    });
    $("data").innerHTML = str;
}

/**
 *重新计算
 *@param code 修改商品编号
 */
function updateNum(code) {
    //找到修改的商品
    var pObj = shopArray.find(n => n.code == code);
    pObj.num = $("shopNum").value;
    showShop();
    totalShop();
}

/**
 *移除商品
 *@param code移除的商品编号
 */
function del(code) {
    //找到指定编号对应的下标
    var index = shopArray.findIndex(n => n.code == code);
    shopArray.splice(index, 1);
    showShop();
    totalShop();
}

/**
 * 购物车总价
 */
function totalShop() {
    var num = 0;
    var newArray = shopArray.map(n => n.num * n.price);
    for (var i = 0; i < newArray.length; i++) {
        num += newArray[i];
    }
    $("total").innerHTML = num;
}